package com.example.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.Admin;
import com.example.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtTokenUtils {

    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);

    private static AdminService staticAdminService;
    @Resource
    private AdminService adminService;
    @PostConstruct
    public void setAdminService(){
        staticAdminService = adminService;
    }


    /**
     * jwt生成token
     * @param userId   用户id
     * @param password 用户密码
     * @return
     */
    public static String genToken(String userId,String password){
        return JWT.create().withAudience(userId)  // 载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //过期时间
                .sign(Algorithm.HMAC256(password));  //签名
    }


    /**
     * 获取当前登录用户的信息
     * @return
     */
    public static Admin getCurrentUser(){
        String token = null;
        try{
            // 拿到请求
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("token");
            if (StrUtil.isBlank(token)){
                token = request.getParameter("token");
            }
            if (StrUtil.isBlank(token)){
                log.error("获取当前登录的token失败,token: {}",token);
                return null;
            }

            // 解析token，获取用户id,从而得到该用户的完整信息
            String userId = JWT.decode(token).getAudience().get(0);
            return staticAdminService.findById(Integer.parseInt(userId));


        }catch (Exception e){
            log.error("获取当前登录的管理员信息失败,token:={}",token,e);
            return null;
        }
    }
}
